import { Injectable, Logger } from '@nestjs/common';
import {
  Cron,
  CronExpression,
  Interval,
  SchedulerRegistry,
} from '@nestjs/schedule';
import { CronJob } from 'cron';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  // 动态注册定时任务 SchedulerRegistry
  constructor(private schedulerRegistry: SchedulerRegistry) {}

  // 定时任务 每5秒输出一次
  //   @Cron('5 * * * * *')
  @Cron(CronExpression.EVERY_5_SECONDS, {
    name: 'task-5-second',
  })
  async handleCron(): Promise<void> {
    this.logger.debug('Called when the current second is 5');
  }

  // 间隔多久执行一次
  @Interval(10000)
  async handleInterval(): Promise<void> {
    this.logger.debug('Called every 10 seconds');
  }

  // 新建一个定时任务
  // 参数：任务名称，每间隔的秒数
  async addCronJob(name: string, seconds: string): Promise<void> {
    const job = new CronJob(`${seconds} * * * * *`, () => {
      this.logger.warn(`time (${seconds}) for job ${name} to run!`);
    });

    this.schedulerRegistry.addCronJob(name, job);
    job.start();

    this.logger.warn(
      `job ${name} added for each minute at ${seconds} seconds!`,
    );
  }

  // 停止一个定时任务
  async stopCronJob(name: string): Promise<void> {
    const job = this.schedulerRegistry.getCronJob(name);
    job.stop();
    console.log(job.lastDate());
    this.logger.warn(`job ${name} stopped, last date is ${job.lastDate()}!`);
  }

  // 删除一个定时任务
  async delCronJob(name: string): Promise<void> {
    this.schedulerRegistry.deleteCronJob(name);
    console.log(`job ${name} deleted!`);
    this.logger.warn(`job ${name} deleted!`);
  }
}
